package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.tomcat.util.digester.Digester;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 处理登录请求
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session){
        //将请求中的明文加密
        String possword = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());

        //处理数据
        LambdaQueryWrapper<Employee> wrapper = new LambdaQueryWrapper<Employee>();
        wrapper.eq(Employee::getUsername, employee.getUsername());
        //根据username查询该员工
        Employee one = employeeService.getOne(wrapper);
        //判断该用户是否存在
        if (one == null){
            log.debug("用户名或者密码错误！");
            return R.error("用户名或者密码错误！");
        }
        //判断用户密码是否正确
        if (!possword.equals(one.getPassword())){
            log.debug("用户名或者密码错误！");
            return  R.error("用户名或者密码错误!");
        }
        //判断该账户是否被禁用
        if (!"1".equals(one.getStatus())){
            log.debug("该账号已被禁用，请联系管理员！");
        }
        //将用户存入session域中
        session.setAttribute("employee",one.getId());


        //到这里，说明已经通过校验
        return R.success(one);
    }

    /**
     * 退出操作 清空session域
     * @param session
     * @return
     */
    @PostMapping("/logout")
    public R<Employee> logout(HttpSession session){
        //将session域删除
        session.invalidate();
        return R.success(null);
    }

    /**
     * 处理分页查询
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(@RequestParam(required = false,defaultValue = "1") Integer page ,
                  @RequestParam(required = false,defaultValue = "10") Integer pageSize, String name){
        //构造page条件
        Page<Employee> pageInfo = new Page<>(page, pageSize);

        //构造查询条件
        LambdaQueryWrapper<Employee> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //判空(非空) 根据name模糊查询
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //细节：根据修改时间反序
        lambdaQueryWrapper.orderByDesc(Employee::getUpdateTime);

        //组装条件
        employeeService.page(pageInfo,lambdaQueryWrapper);

        //返回条件
        return R.success(pageInfo);
    }

    /**
     * 添加操作
     * @param employee
     * @param session
     * @return
     */
    @PostMapping
    public R save(@RequestBody Employee employee,HttpSession session){

        //补全其它信息
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));//赋予员工初始密码
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setCreateUser((Long) session.getAttribute("employee"));
//        employee.setUpdateUser((Long) session.getAttribute("employee"));
        employee.setStatus(1);//使用初始状态

        boolean flag = employeeService.save(employee);

        if (flag){
            return R.success("添加成功");
        }
        return R.error("你的操作有误");
    }

    /**
     * 修改员工账户状态
     * @param employee
     * @param session
     * @return
     */
    @PutMapping
    public R updateStatus(@RequestBody Employee employee,HttpSession session){
        //改变修改时间 修改人物
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser((Long) session.getAttribute("employee"));
        //执行操作
        boolean flag = employeeService.updateById(employee);
        if (flag){
            return R.success("修改成功");
        }
        return R.error("你的操作有误");
    }

    /**
     * 根据id 数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> selectById(@PathVariable long id){
        Employee employee = employeeService.getById(id);
        if (employee == null){
            return R.error("你的操作有误");
        }
        return R.success(employee);
    }
}
